package idp.honeytracks;

import java.io.IOException;
import java.security.GeneralSecurityException;


import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;



public class RestService {
	
	
		
	

private final HttpClient client;
	
	public RestService(String user, String password, String realm, String host, int port) {
		
//		HttpConnection con = new HttpConnection("api.honeytrack.com", 443);
//		try {
//			con.setProtocol(new Protocol("easyhttps", (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), port));
//		} catch (GeneralSecurityException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		this.client = new HttpClient();		
		
		final Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
		client.getState().setCredentials(new AuthScope(host, port, realm), defaultcreds);
	}
	
	
//	public String fetchData(final String url) throws HttpException, IOException {
//		final GetMethod get = new GetMethod(url);
//		
//		int status = client.executeMethod(get);
//		  	
//		final String response = get.getResponseBodyAsString();
//		System.out.println("Status: " + status);
//		
//		get.releaseConnection();
//		return response;
//	}
	
	
	
	public int submitResult(String resultURL, String userId, double predictedRevenue) throws HttpException, IOException {
		final PostMethod post = new PostMethod(resultURL);
		
		post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		
		post.addParameter("Index", userId);
		post.addParameter("Key", userId);
		post.addParameter("Value", Double.toString(predictedRevenue));
		
		int status = client.executeMethod( post );
//		System.out.println("Status: " + status);
//		System.out.println(post.getResponseBodyAsString());
		
		return status;
	}
	
}
